public class Solution904 {
    public int totalFruit(int[] fruits) {
        int j=0;
        int f1=-1,f2=-1,l1=-1,l2=-1;
        int ans=0;
        for (int i=0;i<fruits.length;i++){
            if (f1==-1){
                f1=fruits[i];
                l1=i;
            }else if (f1==fruits[i]){
                l1=i;
            }else if (f2==-1){
                f2=fruits[i];
                l2=i;
            }else if (f2==fruits[i]){
                l2=i;
            }else{
                if (l1>l2){
                    j=l2+1;
                    f2=fruits[i];
                    l2=i;
                }else{
                    j=l1+1;
                    f1=fruits[i];
                    l1=i;
                }
            }
            ans=Math.max(ans,i-j+1);
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution904().totalFruit(new int[]{1,2,3,2,2}));
    }
}
